Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

141
Visualizações
Add attribute to instance of "Number"

I want to see if a number is a multiple of π. So ideally it would behave exactly like an ordinary number, but with extra functionality:

>>> pi
3.14...
>>> pi.isMultipleOfPi
true
>>> b = pi * 5
>>> b.isMultipleOfPi
true

With wishful thinking

>>> c = pi + 1
>>> c.isMultipleOfPi
false
>>> d = pi + 2 * pi
>>> d.isMultipleOfPi
true

Is there a way to achieve something like that in Javascript? I think this would be pretty straight forward in Python, but there seems to be no way to create overloads for addition/multiplication etc. in JS. If there were, I could simply extent the Number class.

Setting something on Number.prototype = function also doesn't seem to work as it sets it for the entire class and not on an instance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You cannot add properties to specific number values; they are not objects and thus they can't have any properties. You can add properties to the Number prototype, as follows:

Object.defineProperty(Number.prototype, "isMultipleOfPi", {
    get: function() {
      return this.valueOf() % Math.PI === 0;
    }
});

const pix2 = Math.PI * 2;
console.log(pix2.isMultipleOfPi);
console.log((7).isMultipleOfPi);

That adds a Number prototype property defined with a "get" function so that the code you posted will work as you expect. The method will be available for all numbers in your program, which doesn't seem like a bad thing if you want that feature at all.

Note also that extending built-in prototype objects is frowned upon by many people. In my example, I extended the prototype in a way that ameliorates some of the problems with extended prototypes.

about 4 years ago · Juan Pablo Isaza Relatório

0

I thought at first you wanted to do this for all numbers, which is answered here.

But if you only want to do this for one specific number, you can, but you probably won't want to. 99.9999999999998% of all numbers you work with in JavaScript are primitives, not objects, and so they don't have any properties (the ones they seem to have only come from Number.prototype [or, in turn, from Object.primitive], which the JavaScript engine will use if you try to access a property on a number primitive).

You could make a number object instead, and put the property on that:

const c = new Number(Math.PI);
c.isMultipleOfPI = true;
console.log(c);
console.log(String(c));
console.log(c.isMultipleOfPI);

The problem with that, though, is demonstrated by the console.log(c); line above. With Chrome's devtools (and perhaps others), you see this:

{
    isMultipleOfPI: true,
}

rather than 3.141592653589793 as you might be expecting.

The reason is that c is an object, not a primitive, and some things that use it (such as console.log) may treat it primarily as an object rather than primarily as a number.

Math and string concatenation work, though:

const c = new Number(Math.PI);
c.isMultipleOfPI = true;
console.log(c * 2);
console.log(c - 2);
console.log(c + 2);
console.log(c / 2);
console.log("The number is " + c);

Just beware that Number instances (objects) are objects, and that very, very little code is written explicitly to work with them properly. Most code using numbers expects number primitives.

Alternatively, you could make an accessor property on Number.prototype (Pointy shows you how) that determines if the number it's called on is a multiple of PI and returns the right flag. That would give you the syntax you showed, but on all numbers. But it is a function call, so accessing the property works it out each time. Just having a isMultipleOfPI(num) function might be clearer.

In a comment you've written:

Because Number.prototype = function(){ return self % Math.PI ~ 0 } is not what I'm looking for. I would wish to distinguish between 3.14 vs 3.14 with isMultipleOfPi property.

The only way to do that is to use Number objects rather than number primitives, as described above.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda